"""
日志工具模块
提供结构化日志记录功能
"""

import os
import json
import logging
import logging.config
from datetime import datetime
from typing import Dict, Any, Optional
from pathlib import Path


def setup_logging(log_level: str = "INFO", log_file: Optional[str] = None) -> logging.Logger:
    """
    设置日志配置

    Args:
        log_level: 日志级别
        log_file: 日志文件路径

    Returns:
        配置后的 logger
    """

    # 创建日志目录
    if log_file:
        log_dir = Path(log_file).parent
        log_dir.mkdir(parents=True, exist_ok=True)

    # 日志配置
    config = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'detailed': {
                'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
            },
            'json': {
                'format': '{"timestamp": "%(asctime)s", "level": "%(levelname)s", "logger": "%(name)s", "message": "%(message)s"}'
            }
        },
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'level': log_level,
                'formatter': 'detailed'
            }
        },
        'root': {
            'level': log_level,
            'handlers': ['console']
        },
        'loggers': {
            'agent_1': {
                'level': log_level,
                'handlers': ['console'],
                'propagate': False
            }
        }
    }

    # 如果指定了日志文件，添加文件处理器
    if log_file:
        config['handlers']['file'] = {
            'class': 'logging.FileHandler',
            'level': log_level,
            'formatter': 'detailed',
            'filename': log_file
        }
        config['loggers']['agent_1']['handlers'].append('file')

    # 应用配置
    logging.config.dictConfig(config)

    # 获取 logger
    logger = logging.getLogger('agent_1')
    return logger


class StructuredLogger:
    """结构化日志记录器"""

    def __init__(self, name: str = "agent_1"):
        self.logger = logging.getLogger(name)
        self.context = {}

    def set_context(self, **kwargs):
        """设置日志上下文"""
        self.context.update(kwargs)

    def clear_context(self):
        """清除日志上下文"""
        self.context.clear()

    def _log(self, level: str, message: str, extra: Optional[Dict[str, Any]] = None):
        """记录结构化日志"""
        log_data = {
            "message": message,
            "timestamp": datetime.now().isoformat(),
            **self.context
        }

        if extra:
            log_data.update(extra)

        # 使用 JSON 格式记录额外信息
        self.logger.log(
            getattr(logging, level.upper()),
            message,
            extra={"structured_data": json.dumps(log_data, ensure_ascii=False)}
        )

    def info(self, message: str, **extra):
        """记录信息日志"""
        self._log("info", message, extra)

    def error(self, message: str, **extra):
        """记录错误日志"""
        self._log("error", message, extra)

    def warning(self, message: str, **extra):
        """记录警告日志"""
        self._log("warning", message, extra)

    def debug(self, message: str, **extra):
        """记录调试日志"""
        self._log("debug", message, extra)


# 全局日志实例
logger = StructuredLogger()


def log_agent_action(action: str, user_input: str, response: Dict[str, Any]):
    """
    记录 Agent 动作

    Args:
        action: 执行的动作
        user_input: 用户输入
        response: Agent 响应
    """
    logger.info(
        f"Agent action: {action}",
        user_input=user_input[:100],
        response_summary=response.get('answer', '')[:100],
        thought=response.get('thought', ''),
        success=response.get('success', False)
    )


def log_api_request(endpoint: str, method: str, status_code: int, duration: float):
    """
    记录 API 请求

    Args:
        endpoint: API 端点
        method: HTTP 方法
        status_code: 响应状态码
        duration: 请求耗时
    """
    logger.info(
        f"API request: {method} {endpoint}",
        status_code=status_code,
        duration=f"{duration:.2f}s",
        endpoint=endpoint,
        method=method
    )


def log_error(error_type: str, error_message: str, **extra):
    """
    记录错误

    Args:
        error_type: 错误类型
        error_message: 错误信息
        extra: 额外信息
    """
    logger.error(
        f"{error_type}: {error_message}",
        error_type=error_type,
        **extra
    )


# 初始化默认日志配置
def init_logging():
    """初始化日志系统"""
    log_level = os.getenv('LOG_LEVEL', 'INFO')
    log_file = os.getenv('LOG_FILE')

    setup_logging(log_level, log_file)

    # 设置第三方库的日志级别
    logging.getLogger('urllib3').setLevel(logging.WARNING)
    logging.getLogger('requests').setLevel(logging.WARNING)
